import os
from django.shortcuts import render
from django.http.response import JsonResponse,FileResponse
from django.core.files.base import ContentFile
from user.models import User
from django import forms
from store.settings import BASE_DIR,MEDIA_ROOT
from .models import Extension,File,ExtensionBill
# Create your views here.
def json(obj):
    return JsonResponse(obj,safe=False)

def get_user(request):
    try:
        return User.objects.get(id=request.session['user_id'])
    except:
        return None

def extension_list(request):
    result=[{
        'id':x.id,
        'name':x.name,
        'display_name':x.display_name,
        'author':x.author.username,
        'price':x.price
    } for x in Extension.objects.all()]
    return json(result)


def my_extension(request):
    user=get_user(request)
    if not user:
        return json({
            'code':403,
            'detail':'no sign in'
        })
    bills=user.bills.all()
    result=[
        {
            'id':bill.extension.id,
            'name':bill.extension.name,
            'display_name':bill.extension.display_name,
            'author':bill.extension.author.username
        } for bill in bills
    ]
    return json(result)
def extension_info(request):
    if extension_id:=request.GET.get('id'):
        extension=Extension.objects.get(id=extension_id)
    else:
        return
    return json({
        'id':extension.id,
        'name':extension.name,
        'display_name':extension.display_name,
        'author':extension.author.username,
        'price':extension.price
    })
def get_price(user_price):
    return 0
def new_extension(request):
    user=get_user(request)
    if not user:
        return json({
            'code':403,
            'detail':'no sign in'
        })
    try:
        name=request.POST['name']
        display_name=request.POST['display_name']
        price=get_price(request.POST.get('price',0))
    except KeyError as e:
        return json({
            'code':400,
            'detail':'args wrong\n\n'+str(e)
        })
    else:
        if len(Extension.objects.filter(name=name)):
            return json({
                'code':409,
                'detail':'name must be unique'
            })
        Extension.objects.create(name=name,display_name=display_name,author=user,price=price)
        return json({
            'code':200,
            'detail':'success'
        })
    
def upload(request):
    user=get_user(request)
    if not user:
        return json({
            'code':403,
            'detail':'no sign in'
        })
    try:
        extension_id=request.POST['extension_id']
        version=request.POST['version']
        file_content=ContentFile(request.FILES.get('file').read())
    except KeyError as e:
        return json({
            'code':400,
            'detail':'params wrong'
        })
    try:
        extension=Extension.objects.get(id=extension_id)
        if extension.author.id!=user.id:
            raise Exception()
    except:
        return json({
            'code':400,
            'detail':'extension_id is wrong'
        })
    file=File(extension=extension,version=version)
    file.file.save(extension.name+"_"+version,file_content)
    file.save()
    return json({
        'code':200,
        'detail':'success'
    })
    
def buy(request):
    user=get_user(request)
    if not user:
        return json({
            'code':403,
            'detail':'not sign in'
        })
    try:
        extension_id=request.POST['extension_id']
        extension=Extension.objects.get(id=extension_id)
    except KeyError as e:
        return json({
            'code':400,
            'detail':'params error'
        })
    except:
        return json({
            'code':400,
            'detail':'extension_id error'
        })
    if user.money<extension.price:
        return json({
            'code':403,
            'detail':'don\'t have enough money'
        })
    bill=ExtensionBill.objects.create(user=user,extension=extension)
    user.money-=extension.price
    user.save()
    return json({
        'code':200,
        'detail':'success'
    })
    
def download(request):
    try:
        file_id=request.GET['id']
        file=File.objects.get(id=file_id)
        extension=file.extension
    except KeyError:
        return json({
            'code':400,
            'detail':'param wrong'
        })
    except:
        return json({
            'code':404,
            'detail':'no file'
        })
    user=get_user(request)
    if extension.price==0 or (user and extension.id in [bill.extension.id for bill in user.bills.all()]):
        path=os.path.join(BASE_DIR,MEDIA_ROOT,str(file.file))
        response=FileResponse(open(path,'rb'))
        response['content-type']='application/octet-stream'
        return response
    else:
        return json({
            'code':403,
            'detail':'not sign or not buy'
        })
